import request from '@/utils/request'

const insertMixin = {
  data: function () {
    return {
      dialogInsert: {
        visible: false
      },
      emptyInsert: {}
    }
  },
  computed: {
    formInsert () {
      const tModel = this.lodash.cloneDeep(this.model)
      const proxy = new Proxy(tModel, {
        get: function (target, prop) {
          return Reflect.get(target, prop)
        },
        deleteProperty: function (target, name) {
          return Reflect.deleteProperty(target, name)
        }
      })
      for (const key of Object.keys(this.model)) {
        if (this.model[key] === '') {
          delete proxy[key]
        }
      }
      return proxy
    },
    preventReInsertSubmitFn () {
      return this.lodash.throttle(this.insertSubmitFn, 3000, {
        leading: true,
        trailing: false
      })
    }
  },
  methods: {
    async initInsertUpdateDialog () {
      this.model = this.lodash.cloneDeep(this.emptyInsert)
      return null
    },
    async handleInsert () {
      const args = [...arguments]
      args.forEach(arg => {
        typeof arg === 'function' && arg()
      })
      await this.initInsertUpdateDialog()
      this.dialogInsert.visible = true
      this.$nextTick(() => {
        const form = this.$refs.formInsert
        form && form.resetFields()
      })
    },
    async insertSubmitFn () {
      try {
        await this.$refs.formInsert.validate()
      } catch (e) {
        console.log(e)
        return
      }
      this.operationLock = true
      request({
        method: 'post',
        url: this.insertURL || this.api.resourceLocation,
        data: this.formInsert
      }).then(res => {
        if (res && res.code === 0) {
          this.tableReload()
          this.model = this.lodash.cloneDeep(this.emptyInsert)
          this.$message({
            message: '新增成功',
            type: 'success'
          })
          this.dialogInsert.visible = false
        }
        this.operationLock = false
      }).catch(e => {
        this.operationLock = false
      })
    },
    insertSubmit () {
      this.preventReInsertSubmitFn()
    },
    insertCancel () {
      this.operationLock = false
      this.model = this.lodash.cloneDeep(this.emptyInsert)
      this.dialogInsert.visible = false
    }
  },
  mounted () {
    this.emptyInsert = this.lodash.cloneDeep(this.model)
  }
}
export default insertMixin
